package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.amap.api.location.AMapLocation;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.RDistributionSub;
import com.isunland.managesystem.entity.rDistributionMain;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LocationUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.PictureUtil;
import com.isunland.managesystem.utils.SimpleUploadHandler;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.MultiLinesView;
import java.io.File;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/7/21 10:55
 */
public class SignDeliveryDetailFragment extends BaseFragment {
  @BindView(R.id.tv_location_attendanceDetail) TextView tvLocation;
  @BindView(R.id.iv_picture_attendanceDetail) ImageView ivPicture;
  @BindView(R.id.ib_photo_attendanceDetail) ImageButton ibTakePhoto;
  @BindView(R.id.slv_remark) MultiLinesView slvRemark;
  //@BindView(R.id.slv_signTime) SingleLineView slvSignTime;
  @BindView(R.id.bt_sign_in) Button btnSign;
  private RDistributionSub mItem;
  private File mCameraFile;
  private Callbacks mCallbacks;

  public interface Callbacks {
    void onRefresh();
  }

  @Override public void onAttach(Context activity) {
    super.onAttach(activity);
    mCallbacks = (Callbacks) activity;
  }

  @Override public void onDetach() {
    super.onDetach();
    mCallbacks = null;
  }

  @Override public void initData() {
    super.initData();
    rDistributionMain mItemMain = mBaseParams.getItem() instanceof rDistributionMain
        ? (rDistributionMain) mBaseParams.getItem() : new rDistributionMain();
    mItem = new RDistributionSub();
    mItem.setId(UUID.randomUUID().toString());
    mItem.setMemberCode(mCurrentUser.getMemberCode());
    mItem.setMemberName(mCurrentUser.getMemberName());
    mItem.setMainId(mItemMain.getId());
    mItem.setRegStaffId(mCurrentUser.getMemberCode());
    mItem.setRegStaffName(mCurrentUser.getRealName());
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_sign_delivery_detail, container, false);
    ButterKnife.bind(this, view);
    return view;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    //绑定事件.
    LocationUtil.newInstance(mActivity)
        .setSimpleLocationListener(new LocationUtil.SimpleCustomLocationListener() {
          @Override public void onLocationValid(AMapLocation location) {

            mItem.setLatitude(MyStringUtil.valueOf(location.getLatitude()));
            mItem.setLongitude(MyStringUtil.valueOf(location.getLongitude()));
            mItem.setSignLocaltion(location.getAddress());
            tvLocation.setText(location.getAddress());
          }

          @Override public void onLocationError() {
            tvLocation.setText(R.string.noLocation);
          }
        })
        .startLocation();

    ibTakePhoto.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        mCameraFile = PictureUtil.takePhoto(SignDeliveryDetailFragment.this, mActivity);
      }
    });
    btnSign.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        sign();
      }
    });
  }

  private void sign() {
    MyUtils.showDialogLoading(mActivity, getString(R.string.loadingSignIn));
    if ((mCameraFile != null)
        && (ivPicture.getVisibility() == View.VISIBLE)
        && (MyStringUtil.isEmpty(mItem.getSignPhoto()))) {
      //未上传.路径为空.
      volleyPostUploadPhoto();
    } else {
      volleyPostSign();
    }
  }

  private void volleyPostUploadPhoto() {
    new FileNetWorkUtil(getActivity()).upLoadFile(mCameraFile.getAbsolutePath(),
        ApiConst.URL_UPLOAD_FILE, "imsmm.r_distribution_sub", mItem.getId(),
        new SimpleUploadHandler() {
          @Override public void onUploadSuccess(@SuppressWarnings("UnusedParameters") String path) {
            super.onUploadSuccess(path);
            mItem.setSignPhoto(path);
            mItem.setSignPhotoName(FileUtil.getFileNameByFilePath(path));
            volleyPostSign();
          }

          @Override public void onUploadError(Throwable e) {
            super.onUploadError(e);
            MyUtils.dismissDialog();
          }

          @Override public void onUploadFailure() {
            super.onUploadFailure();
            MyUtils.dismissDialog();
          }
        }, false);
  }

  private void volleyPostSign() {
    mItem.setRemark(slvRemark.getTextContent());
    MyUtils.showDialogLoading(mActivity);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_SIGN_DELIVERY);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.putAll(mItem);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        Base result = new Gson().fromJson(json, Base.class);
        ToastUtil.show(result.getMessage());
        if (result.getResult() == Base.SUCCESS) {
          //((BasePagerActivity)mActivity).setNavigateTo(1);
          //重置界面
          slvRemark.setTextContent("");
          ivPicture.setVisibility(View.GONE);
          mCallbacks.onRefresh();
        }
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == PictureUtil.REQUEST_CAMERA) {
      Bitmap bitmap = PictureUtil.getBitmap(mCameraFile);
      ivPicture.setImageBitmap(bitmap);
      ivPicture.setVisibility(bitmap == null ? View.GONE : View.VISIBLE);
    }
  }
}
